﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace YLW.Plat.Jhfw.HL7V3
{
    public class HL7V3Helper
    {
        /// <summary>
        /// XML 序列化方法
        /// </summary>
        public static string SerializeToXml<T>(T obj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            var settings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                CheckCharacters = false, // 禁用字符检查
                Indent = true // 可选，美化输出
            };

            using (var writer = new Utf8StringWriter())
            using (var xmlWriter = XmlWriter.Create(writer, settings))
            {
                serializer.Serialize(xmlWriter, obj);
                string xml = writer.ToString();
                // 正则匹配所有 _xXXXX_ 并转换为 Unicode 字符
                xml = Regex.Replace(xml, @"_x([0-9A-F]{4})_",
                    m => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString());
                return xml;
            }
        }

        /// <summary>
        /// 实体 反序列化方法
        /// </summary>
        public static T? DeserializeToModel<T>(string xml) where T : class
        {
            // 使用正则表达式删除所有的 xsi: 属性
            xml = Regex.Replace(xml, @"\s*xsi:\w+=""[^""]*""", "");

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringReader reader = new StringReader(xml))
            {
                try
                {
                    return serializer.Deserialize(reader) as T;
                }
                catch (InvalidOperationException)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 解决 XML 默认 UTF-16 编码，强制使用 UTF-8
        /// </summary>
        public class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding => Encoding.UTF8;
        }

        /// <summary>
        /// 判断XML中是否包含拓展参数节点
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static bool HasExtensionNode(string xml)
        {
            try
            {
                var doc = XDocument.Parse(xml);
                XNamespace ns = doc.Root?.Name.Namespace ?? "";

                return doc.Descendants().Any(e => e.Name.LocalName == "extension");
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 转换XML中拓展参数为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T ConvertXmlExtensionToModel<T>(string xml) where T : new()
        {
            var doc = XDocument.Parse(xml);
            XNamespace ns = doc.Root.Name.Namespace;

            var extensionElement = doc.Descendants(ns + "extension").FirstOrDefault();
            if (extensionElement == null) return new T();

            T model = new T();
            var modelType = typeof(T);

            foreach (var prop in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var element = extensionElement.Element(ns + prop.Name);
                if (element == null) continue;

                var valueText = element.Element(ns + "value")?.Value ?? "";

                if (!string.IsNullOrEmpty(valueText) && prop.CanWrite)
                {
                    try
                    {
                        var targetType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                        object typedValue = string.IsNullOrEmpty(valueText) ? null : Convert.ChangeType(valueText, targetType);
                        prop.SetValue(model, typedValue);
                    }
                    catch
                    {
                        // 类型转换失败可忽略或记录日志
                    }
                }
            }

            return model;
        }

        /// <summary>
        /// 转换XML中拓展参数为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static List<T> ConvertXmlExtensionsToModels<T>(string xml) where T : new()
        {
            var doc = XDocument.Parse(xml);
            XNamespace ns = doc.Root.Name.Namespace;

            var extensionElementList = doc.Descendants(ns + "extension");
            if (extensionElementList == null) return new List<T>();

            var result = new List<T>();

            foreach (var extensionElement in extensionElementList)
            {
                T model = new T();
                var modelType = typeof(T);

                foreach (var prop in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    var element = extensionElement.Element(ns + prop.Name);
                    if (element == null) continue;

                    var valueText = element.Element(ns + "value")?.Value ?? "";

                    if (!string.IsNullOrEmpty(valueText) && prop.CanWrite)
                    {
                        try
                        {
                            var targetType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                            object typedValue = string.IsNullOrEmpty(valueText) ? null : Convert.ChangeType(valueText, targetType);
                            prop.SetValue(model, typedValue);
                        }
                        catch
                        {
                            // 类型转换失败可忽略或记录日志
                        }
                    }
                }

                result.Add(model);
            }

            return result;
        }
    }
}
